// Timer Adjustment State Machine.
//

extern EncoderStateStruct wheel;

unsigned long int BoxAdjust(	long int number,
								signed long long int offset,
							 	long int range)

{
	signed long long int x;
	x = number;

	x = x + offset;
	if(x > range) x = range;
	if(x < 0) x = 0;
	return x; 
}

void SM_Get_Value(char sel_prog)
{
	// Get setting to adjust
	//
	long long int setting;
	signed long int wh_dir;


	FlashMode(adjust);

	// Get previous setting
	//
	setting = TIM_Fetch(sel_prog);

	// Display setting
	//
	ShiftOut( BarGraph(setting, 30000) );

 	WaitPB_Release();

	do
	{
		// See what the wheel is doing
		//
		wheel.current_position = ENC_Read();
		wh_dir = ENC_Scan( &wheel );

		setting = BoxAdjust(setting, (wh_dir * 500), 30000);
		ShiftOut( BarGraph(setting, 30000) );

	} while( MultiPushButton() == off);

 	WaitPB_Release();

	// Save now adjusted setting
	//
	TIM_Store(sel_prog, setting);
}

char TIM_ChangeProg(char curr_prog)
{
	// Initialise ChangeProg SM
	//
	int AdjustKillSig = 0;
	signed int wh_dir;
	PushType lastpush = off;
	PushType thispush = off;

	// Update Bargraph
	//
	FlashMode(selection);

	BarPoint(curr_prog);

	// Prevent advancement until the button is released.
	// This probably should go elsewhere.
	//
	WaitPB_Release();	

	// Execute the Adjust SM Loop
	//
	do
	{
		// See what the wheel is doing
		//
		wheel.current_position = ENC_Read();
		wh_dir = ENC_Scan( &wheel );

		// Display the currently selected program
		// adjusted into range.
		//
		curr_prog = BoxAdjust(curr_prog, wh_dir, 7);
		if(systick2 > 45 ) BarPoint(curr_prog);
			else ShiftOut(0);
		if(systick2 == 0) systick2 = 80;

		// Process wheelbutton.
		//
		thispush = MultiPushButton();

		if( thispush == push_held ) AdjustKillSig = 1;
		else if( (thispush == off ) && ( lastpush == on ))
		{
			SM_Get_Value(curr_prog);
			FlashMode(selection);
		}

		// Remember how it was
		//
		lastpush = thispush;

	} while(!AdjustKillSig);

	return curr_prog;
}